/**
 * @file object_pool.h
 * @brief 高性能对象池实现
 * 
 * 这个对象池实现针对高频交易系统的特殊需求进行了优化：
 * 1. 预分配固定数量的对象，避免运行时内存分配
 * 2. 线程安全设计，支持并发访问
 * 3. 无锁实现，减少同步开销
 * 4. 缓存友好的内存布局
 */

#pragma once

#include <array>
#include <atomic>
#include <cstddef>
#include <memory>
#include <new>
#include <optional>
#include <type_traits>

namespace hft {
namespace utils {

/**
 * @brief 高性能对象池
 * 
 * @tparam T 池中对象的类型
 * @tparam N 池的大小
 */
template<typename T, size_t N>
class ObjectPool {
    static_assert(std::is_nothrow_constructible<T>::value, 
                  "Type must be nothrow constructible");
    static_assert(std::is_nothrow_destructible<T>::value, 
                  "Type must be nothrow destructible");

public:
    /**
     * @brief 表示从对象池获取的对象
     * 当这个包装器被销毁时，对象会自动返回到池中
     */
    class PooledObject {
    public:
        PooledObject() noexcept : pool_(nullptr), index_(0) {}
        
        PooledObject(ObjectPool* pool, size_t index) noexcept
            : pool_(pool), index_(index) {}
        
        PooledObject(const PooledObject&) = delete;
        PooledObject& operator=(const PooledObject&) = delete;
        
        PooledObject(PooledObject&& other) noexcept
            : pool_(other.pool_), index_(other.index_) {
            other.pool_ = nullptr;
        }
        
        PooledObject& operator=(PooledObject&& other) noexcept {
            if (this != &other) {
                release();
                pool_ = other.pool_;
                index_ = other.index_;
                other.pool_ = nullptr;
            }
            return *this;
        }
        
        ~PooledObject() noexcept {
            release();
        }
        
        T* operator->() noexcept {
            return &(pool_->objects_[index_]);
        }
        
        const T* operator->() const noexcept {
            return &(pool_->objects_[index_]);
        }
        
        T& operator*() noexcept {
            return pool_->objects_[index_];
        }
        
        const T& operator*() const noexcept {
            return pool_->objects_[index_];
        }
        
        explicit operator bool() const noexcept {
            return pool_ != nullptr;
        }
        
    private:
        void release() noexcept {
            if (pool_) {
                pool_->release(index_);
                pool_ = nullptr;
            }
        }
        
        ObjectPool* pool_;
        size_t index_;
    };
    
    ObjectPool() noexcept {
        // 初始化所有对象
        for (size_t i = 0; i < N; ++i) {
            // 使用placement new在预分配的内存中构造对象
            new (&objects_[i]) T();
            // 初始化空闲列表
            next_free_[i] = i + 1;
        }
        next_free_[N - 1] = SIZE_MAX; // 标记列表结束
    }
    
    ~ObjectPool() noexcept {
        // 显式调用所有对象的析构函数
        for (size_t i = 0; i < N; ++i) {
            objects_[i].~T();
        }
    }
    
    /**
     * @brief 从池中获取一个对象
     * 
     * @return std::optional<PooledObject> 如果池中有可用对象，返回对象包装器；否则返回空
     */
    std::optional<PooledObject> acquire() noexcept {
        size_t current_head = free_list_head_.load(std::memory_order_relaxed);
        
        while (current_head != SIZE_MAX) {
            size_t next = next_free_[current_head];
            
            if (free_list_head_.compare_exchange_weak(
                    current_head, next, 
                    std::memory_order_acquire, 
                    std::memory_order_relaxed)) {
                // 重置对象到初始状态
                new (&objects_[current_head]) T();
                return PooledObject(this, current_head);
            }
            
            // 如果CAS失败，current_head已被更新为最新值，继续循环
        }
        
        return std::nullopt; // 池已空
    }
    
    /**
     * @brief 获取池的容量
     */
    constexpr size_t capacity() const noexcept {
        return N;
    }
    
    /**
     * @brief 获取当前可用对象数量
     * 注意：在并发环境中，这个值可能在返回后立即变化
     */
    size_t available() const noexcept {
        size_t count = 0;
        size_t current = free_list_head_.load(std::memory_order_relaxed);
        
        while (current != SIZE_MAX) {
            ++count;
            current = next_free_[current];
        }
        
        return count;
    }
    
private:
    /**
     * @brief 将对象返回到池中
     * 
     * @param index 要返回的对象索引
     */
    void release(size_t index) noexcept {
        // 调用对象的析构函数
        objects_[index].~T();
        
        // 将对象添加到空闲列表头部
        size_t current_head = free_list_head_.load(std::memory_order_relaxed);
        do {
            next_free_[index] = current_head;
        } while (!free_list_head_.compare_exchange_weak(
                    current_head, index,
                    std::memory_order_release,
                    std::memory_order_relaxed));
    }
    
    // 对象存储
    alignas(64) std::array<T, N> objects_;
    
    // 空闲列表
    alignas(64) std::array<size_t, N> next_free_;
    
    // 空闲列表头指针
    alignas(64) std::atomic<size_t> free_list_head_{0};
};

} // namespace utils
} // namespace hft